package edu.indiana.d2i;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import edu.indiana.d2i.app.ScriptBase;
import edu.indiana.d2i.registry.RegistryClient;
import edu.indiana.d2i.util.Utilities;

public class ApplicationManager {
	// These are the settings that must be conformed to run this program.
	private static Map<String, String> scriptNameMapping = new HashMap<String, String>();
	static {
		scriptNameMapping.put("simplescript", "edu.indiana.d2i.app.SimpleScript");
	}

	public static void main(String[] args) {
		/* get inputs */
		String usage = "Usage: ApplicationManager appName collectionName";
		if (args.length < 2) {
			System.err.println(usage);
			System.exit(-1);
		}
		String appName = args[0];
		String collectionName = args[1];
		
		/* validation */
		if (!scriptNameMapping.containsKey(appName)) {
			System.err.println("Application name is wrong!");
			System.exit(-1);
		}

		/* step 0: read service names */
		String solrServiceName, repositoryName;
		solrServiceName = repositoryName = "";
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream("config.properties"));
			solrServiceName = prop.getProperty("solrindex");
			repositoryName = prop.getProperty("repository");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		
		/* step 1: interact with the registry */
		RegistryClient client = new RegistryClient();
		String jarFile = client.getScriptFile(appName);
		String solrIndexServiceURI = client
				.getSolrIndexServiceURI(solrServiceName);
		String repoURI = client.getRepositoryURI(repositoryName);
		List<String> volumnIDs = client
				.getVolumeIDsFromCollection(collectionName);

		/* step 1.1: validate everything */
		if (jarFile == null || solrIndexServiceURI == null || repoURI == null) {
			System.err.println("Error occurs while interacting with registry.");
			System.exit(1);
		}
		
		/* step 2: invoke the application */
		try {
			Class<?> mainClass = Utilities.generateClassFromJarFile(jarFile,
					scriptNameMapping.get(appName));
			Constructor<?> constructor = mainClass.getConstructor(String.class,
					String.class, List.class);		
			ScriptBase object = (ScriptBase)constructor.newInstance(
					solrIndexServiceURI, repoURI, volumnIDs);
			object.run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
